package org.jumuning.redis.config;

import org.jumuning.redis.handler.RedisMessageHandler;
import org.jumuning.redis.listener.RedisMessageListener;
import org.jumuning.redis.model.MessagesData;
import org.jumuning.redis.props.RedisMessageProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 自动装配：提供 RedisMessageListener 与 RedisMessageListenerContainer
 */
@AutoConfiguration
@EnableConfigurationProperties(RedisMessageProperties.class)
public class RedisMessageAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public RedisMessageListener redisMessageListener(StringRedisTemplate stringRedisTemplate,
                                                     RedisMessageProperties properties,
                                                     RedisMessageHandler<MessagesData> handler) {
        // channel 由 properties 提供
        return new RedisMessageListener(stringRedisTemplate, handler, properties.getChannel());
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            RedisMessageListener redisMessageListener,
            RedisMessageProperties properties) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(redisMessageListener, new ChannelTopic(properties.getChannel()));
        return container;
    }
}
